import { Inject, Provide } from '@midwayjs/core';
import { Repository } from 'typeorm';
import { Wristband } from '../../entity/firmware/wristband.entity';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { v4 as uuidv4 } from 'uuid';
import { WristbandAdvService } from './wristband_adv.service';
// import { resBuild } from '@utils/resBuild';
@Provide()
export class WristbandService {
  @InjectEntityModel(Wristband)
  wristbandRepo: Repository<Wristband>;
  @Inject()
  wristbandAdvService: WristbandAdvService

  // **创建手环**
  async createWristband(data: Partial<Wristband>) {
    data.id = uuidv4()
    data.time = new Date()
    const wristband = this.wristbandRepo.create(data);
    return await this.wristbandRepo.save(wristband);
  }

  // **获取所有手环**
  async getAllWristbands(param) {
    const { fw_name, mac, fw_version, edgroup_id, school_id, class_id, name, pageNum, pageSize } = param;
    const query = this.wristbandRepo
      .createQueryBuilder('wristband')
      .leftJoinAndSelect('wristband.student_wristband', 'sw') // 关联学生手环表
      .leftJoinAndSelect('sw.student', 'student') // 关联学生表
      .leftJoinAndSelect('student.class', 'class') // 关联班级表
      .leftJoinAndSelect('class.school', 'school') // 关联学校表
      .leftJoinAndSelect('school.edgroup', 'edgroup') // 关联教育集团表
      .where('wristband.deleted != :deleted', { deleted: 1 })
      // 查找手环 fw_name 值为 c1 的手环
      // .andWhere('wristband.fw_name = :fw_name', { fw_name: 'c1' })
    if (edgroup_id) {
      query.andWhere('edgroup.id = :edgroup_id', { edgroup_id });
    }
    if (class_id) {
      query.andWhere('class.id = :class_id', { class_id });
    }
    if (school_id) {
      query.andWhere('school.id = :school_id', { school_id });
    }
    if (name) {
      query.andWhere('student.name LIKE :name', { name: `%${name}%` });
    }
    // 这里是模糊查询，前后都有 % 符号
    if (fw_name) {
      query.andWhere('wristband.fw_name LIKE :fw_name', { fw_name: `%${fw_name}%` })
    }
    if (mac) {
      query.andWhere('wristband.mac LIKE :mac', { mac: `%${mac}%` })
    }
    if (fw_version) {
      query.andWhere('wristband.fw_version LIKE :fw_version', { fw_version: `%${fw_version}%` })
    }
    // 时间降序排序
    query.orderBy('wristband.time', 'DESC');
    // 分页
    if (pageNum && pageSize) {
      query.skip((pageNum - 1) * pageSize).take(pageSize);
    }
    // 统计总数
    const total = await query.getCount();
    // console.log('total', total)
    // 返回数据
    return {
      total,
      data: await query.getMany(),
    };
  }


  // 获取指定网关最近5分钟上报的手环
  async getLastWristbands(params) {
    try {
      const result = await this.wristbandAdvService.getLastWbAll(params)
      // let resultWbList = result.data.map((item) => {
      //   return {
      //     mac: item.mac
      //   }
      // })
      return result
    } catch (err) {
      console.log('获取最近5分钟上报的手环失败', err)
      // return resBuild.fail('获取最近5分钟上报的手环失败', err)
    }

  }

  // **根据 MAC 地址获取手环**
  async getWristbandByMac(mac: string) {
    return await this.wristbandRepo.findOne({ where: { mac } });
  }

  // **更新手环信息**
  async updateWristband(mac: string, updateData: Partial<Wristband>) {
    const wristband = await this.getWristbandByMac(mac);
    if (!wristband) return null;

    Object.assign(wristband, updateData);
    return await this.wristbandRepo.save(wristband);
  }

  // **删除手环**
  async deleteWristband(mac: string) {
    const result = await this.wristbandRepo.delete(mac);
    return result.affected > 0;
  }
}
